import 'dart:convert';
import 'package:flutter/material.dart';
import '../../models/user_info_model.dart';
import '../../l10n/app_localizations.dart';
import '../view/custom_text_field.dart';
import '../view/ercode_text_field.dart';
import '../../manger/network_utils.dart';
import '../../components/toast_utils.dart';
import '../view/protocol_view.dart';
import '../view/protocol_dialog.dart';
import '../../manger/user_manger.dart';
import '../../components/click_word_captcha.dart';

class AuthCenterView extends StatefulWidget {
  final UsssBingInfo? bingInfo;
  final int loginType;
  final VoidCallback? onThridLoginSuccess;

  const AuthCenterView({
    Key? key,
    this.bingInfo,
    required this.loginType,
    this.onThridLoginSuccess,
  }) : super(key: key);

  @override
  State<AuthCenterView> createState() => _AuthCenterViewState();
}

class _AuthCenterViewState extends State<AuthCenterView> {
  UsssBingInfo? _bingInfo;

  int select = 0;
  bool isEmailEditable = true; // 是否可编辑邮箱
  bool isShowPassWord = true; // 是否显示密码
  bool isSwitchable = true; // 是否可切换
  bool isCheakEmail = false; // 是否校验邮箱
  int bindType = 0;
  final TextEditingController _ercodeController = TextEditingController();
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final GlobalKey<ErcodeTextFieldState> _ercodeKey = GlobalKey();
  var captchaVerification = '';

  @override
  void initState() {
    super.initState();
    _bingInfo = widget.bingInfo; // 初始化
    changeUI2();
  }

  void changeUI2(){
    /// 根据传入的 bingInfo 预设逻辑
    if (_bingInfo?.bindType == "3") {
      setState(() {
        bindType = 3; 
        select = 1; // 强制选择验证码绑定
        isSwitchable = false;
        isEmailEditable = false;
        _usernameController.text = _bingInfo!.email!;
      });
  
    } else if (_bingInfo?.bindType == "2") {
      setState(() {
        bindType = 2; 
        select = 0; // 选择密码绑定
        isSwitchable = true;
        isEmailEditable = false;
        _usernameController.text = _bingInfo!.email!;
      });
    } else {
      setState(() {
        bindType = 0;
        select = 0; // 默认选择密码绑定
        isSwitchable = true;
        isEmailEditable = true;
        isShowPassWord = false;
      });
    }
  }

  void changeUI3(){
    if (_bingInfo?.bindType == "3") {
      setState(() {
        bindType = 3; 
        select = 1; // 选择验证码绑定
        isSwitchable = true;
        isEmailEditable = true;
        
      });
  
    } else if (_bingInfo?.bindType == "2") {
      setState(() {
        bindType = 2;
        select = 0; // 选择密码绑定
        isShowPassWord = true;
        isSwitchable = true;
        isEmailEditable = true;
        isCheakEmail = true;
      });
    }
  }

  void selectIndex(int index){
    setState(() {
      select = index;
    });

    if (bindType == 3){
      setState(() {
        bindType = 2;
      });
    } else if (bindType == 2) {
      setState(() {
        bindType = 3;
      });
    }

    if (index == 0 && bindType == 3) {
      setState(() {
        isShowPassWord = false;
        _usernameController.text = "";
      });
    }

  }

  @override
  Widget build(BuildContext context) {
    final local = AppLocalizations.of(context)!;

    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
      ),
      constraints: const BoxConstraints(minHeight: 200),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 顶部切换按钮视图
          Container(
            height: 50,
            decoration: const BoxDecoration(
              color: Color(0xFFF4F4FE),
              borderRadius: BorderRadius.vertical(top: Radius.circular(15)),
            ),
            child: Row(
              children: [
                // 左边：密码绑定
                Expanded(
                  flex: select == 0 ? 6 : 5,
                  child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      if (isSwitchable) {
                        selectIndex(0);
                      }
                    },
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        if (select == 0)
                          Column(
                            children: [
                              Stack(
                                alignment: Alignment.center,
                                children: [
                                  Image.asset(
                                    'assets/images/login_right2.png',
                                    height: 50,
                                    fit: BoxFit.fill,
                                  ),
                                  Text(
                                    '${local.password}${local.bind}',
                                    style: const TextStyle(
                                      fontSize: 14,
                                      color: Colors.black,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          )
                        else
                          Text(
                            '${local.password}${local.bind}',
                            style: const TextStyle(
                              fontSize: 14,
                              color: Color(0xFF787FC5),
                            ),
                          ),
                      ],
                    ),
                  ),
                ),

                // 右边：验证码绑定
                Expanded(
                  flex: select == 1 ? 6 : 5,
                  child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      if (isSwitchable) {
                        selectIndex(1);
                      }
                    },
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        if (select == 1)
                          Column(
                            children: [
                              Stack(
                                alignment: Alignment.center,
                                children: [
                                  Image.asset(
                                    'assets/images/login_left2.png',
                                    height: 50,
                                    fit: BoxFit.fill,
                                  ),
                                  Text(
                                    '${local.verificationCode}${local.bind}',
                                    style: const TextStyle(
                                      fontSize: 14,
                                      color: Colors.black,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          )
                        else
                          Text(
                            '${local.verificationCode}${local.bind}',
                            style: const TextStyle(
                              fontSize: 14,
                              color: Color(0xFF787FC5),
                            ),
                          ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),

          const SizedBox(height: 12),
          // 内容区域
          if (select == 0)
            _buildLeftContent()
          else
            _buildRightContent(),

          ProtocolView(),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 5,vertical: 10),
            child: SizedBox(
              height: 46,
              width: 260,
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF5D5FEE),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(23),
                  ),
                ),
                onPressed: () {
                  if (_usernameController.text.isEmpty) {
                    ToastUtils.showCenterToast(context, '${local.pleaseEnter}${local.mailbox}');
                    return;
                  }

                  if (!ProtocolView.isSelected) {
                    showDialog(
                      context: context,
                      builder: (context) => ProtocolDialog(onCancel: () {
                        Navigator.pop(context);
                      },onSure: () {
                        setState(() {
                          ProtocolView.isSelected = true;
                          bindLogin(bindType);
                        });
                      },),
                    );
                    return;
                  }
                 bindLogin(bindType);
                },
                child: Text(
                  '${local.confirm}${local.bind}',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                  ),
                ),
              ),
            ),
          ),    
          SizedBox(height: 10,)      
        ],
      ),
    );
  }

  Widget _buildLeftContent() {
    final local = AppLocalizations.of(context)!;

    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        children: [
          // 邮箱标题
          Row(
            children: [
              Padding(
                padding: EdgeInsets.only(left: 30),
                child: Image.asset(
                  'assets/images/login_mail_select.png',
                  width: 18,
                  height: 18,
                ),
              ),
              const SizedBox(width: 8),
              Text(
                local.mailbox,
                style: const TextStyle(
                  color: Color(0xFF000000),
                  fontSize: 14,
                ),
              ),
            ],
          ),
          const SizedBox(height: 10),
          // 邮箱输入框
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
            child: CustomTextField(
              controller: _usernameController,
              hintText: '${local.pleaseEnter}${local.mailbox}',
              enabled: isEmailEditable,
              onEditingComplete: () async {
                if (isEmailEditable) {
                  // 用户失去焦点后校验邮箱
                  await _checkEmailExist(_usernameController.text);
                }
              },
              onChanged: (value) {},
            ),
          ),
isShowPassWord
    ? Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(height: 12),
          // 密码标题
          Row(
            children: [
              Padding(
                padding: const EdgeInsets.only(left: 30),
                child: Image.asset(
                  'assets/images/login_phone_select.png',
                  width: 18,
                  height: 18,
                ),
              ),
              const SizedBox(width: 8),
              Text(
                local.password,
                style: const TextStyle(
                  color: Color(0xFF000000),
                  fontSize: 14,
                ),
              ),
            ],
          ),
          const SizedBox(height: 10),

          // 密码输入框
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
            child: CustomTextField(
              controller: _passwordController,
              hintText: '${local.pleaseEnter}${local.password}',
              obscureText: true,
            ),
          ),
        ],
      )
    : const SizedBox.shrink(), // 不显示任何内容

        ],
    ),
    );
  }

  Widget _buildRightContent() {
    final local = AppLocalizations.of(context)!;

    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        children: [
          // 邮箱标题
          Row(
            children: [
              Padding(
                padding: EdgeInsets.only(left: 30),
                child: Image.asset(
                  'assets/images/login_mail_select.png',
                  width: 18,
                  height: 18,
                ),
              ),
              const SizedBox(width: 8),
              Text(
                local.mailbox,
                style: const TextStyle(
                  color: Color(0xFF000000),
                  fontSize: 14,
                ),
              ),
            ],
          ),
          const SizedBox(height: 10),
          // 邮箱输入框
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
            child: CustomTextField(
              controller: _usernameController,
              hintText: '${local.pleaseEnter}${local.mailbox}',
              enabled: isEmailEditable,
              onEditingComplete: () async {
                if (isEmailEditable) {
                  // 用户失去焦点后校验邮箱
                  await _checkEmailExist(_usernameController.text);
                }
              },
              onChanged: (value) {},
            ),
          ),
          const SizedBox(height: 12),

          // 验证码标题
          Row(
            children: [
              Padding(
                padding: EdgeInsets.only(left: 30),
                child: Image.asset(
                  'assets/images/ercode.png',
                  width: 18,
                  height: 18,
                ),
              ),
              const SizedBox(width: 8),
              Text(
                local.verificationCode,
                style: const TextStyle(
                  color: Color(0xFF000000),
                  fontSize: 14,
                ),
              ),
            ],
          ),
          const SizedBox(height: 10),

          // 验证码输入框
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
            child: ErcodeTextField(
              key: _ercodeKey,
              controller: _ercodeController,
              onSendCode: (value) {
                sendCode();
              },
              onChanged: (value) {},
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _checkEmailExist(String email) async {
    if (email.isEmpty) return;

    if (isCheakEmail && bindType == 2){
      try {
        final timestamp = DateTime.now().millisecondsSinceEpoch.toString();
        final res = await NetworkUtils.post(RequestCmd.t, body: {'t': base64Encode(utf8.encode(email)),"b":timestamp});
        final code = res['code'];
        if (code == 200) {
          if (res['data'].isNotEmpty){

          }else{
            changeUI();
          }
        }
      } catch (e) {
        changeUI();
      }
    } else {
      try {
        await NetworkUtils.post(RequestCmd.t, body: {'t': base64Encode(utf8.encode(email))});
      } catch (e) {
        print('检查邮箱失败: $e');
      }

    }
  }

  void changeUI() {
    setState(() {
      bindType = 0;
      isShowPassWord = false;
    });
  }

  void sendCode() async {
    var params = {
      'email': _usernameController.text,
      'sendType': 3,
      'captchaVerification': captchaVerification,
    };

    ToastUtils.showLoadingToast(context);

    try {
      final response = await NetworkUtils.post(
        RequestCmd.sendEmailCode,
        body: params,
      );
      ToastUtils.dismissLoadingToast();
      captchaVerification = "";
      final model = PhoneCodeModel.fromJson(response);
      if (model.code == 200) {
        if (model.data?.boolValue != null) {
          // 处理bool情况
          final boolValue = model.data!.boolValue!;
          if(boolValue){
            loadingClickWord(context,1);
          }
        } else {
          ToastUtils.showCenterToast(context, model.msg ?? '发送成功');
          _ercodeKey.currentState?.startCountdown();
        }
      } else {
        ToastUtils.showCenterToast(context, model.msg ?? '绑定失败，请联系客服');
      }
    } catch (e) {
      ToastUtils.dismissLoadingToast();
    }
  }

  void loadingClickWord(BuildContext context,int type, {barrierDismissible = true}) {
    showDialog<Null>(
      context: context,
      barrierDismissible: barrierDismissible,
      builder: (BuildContext context) {
        return ClickWordCaptcha(
          onSuccess: (v){
            captchaVerification = v;
            if (type == 0) {
              bindLogin(bindType);
            } else {
              sendCode();
            }
          },
          onFail: (){
          },
        );
      },
    );
  }

  Future<void> bindLogin(int value) async {
    _bingInfo?.bindType = value.toString();
    var params = {};
    if (value == 0) {
      params = {
        'loginType': widget.loginType,
        'bindType': _bingInfo?.bindType,
        'code': _ercodeController.text,
        'bizId':_bingInfo?.bizId,
        'email': _usernameController.text,
        'captchaVerification':captchaVerification
      };
    } else if (value == 2 || value == 3){
      params = {
        'loginType': widget.loginType,
        'bindType': _bingInfo?.bindType,
        'code': _ercodeController.text,
        'bizId':_bingInfo?.bizId,
        'email': _usernameController.text,
        'password': _passwordController.text,
        'captchaVerification': captchaVerification,
      };
    } 
    try {
      final response = await NetworkUtils.post(
        RequestCmd.authorizelogin,
        body: params,
      );
      captchaVerification = "";
      if (response.toString().contains('804')) {
        final model = UserBingData.fromJson(response);
        if (model.data != null) {
          _bingInfo = model.data;
          changeUI3();
          return;
        } else {
          ToastUtils.showCenterToast(context, model.msg);
          return;
        }

      } else {
        final model = LoginModel.fromJson(response);
        if (model.code == 200) {
          if (model.data?.model != null) {
            final tokenModel = model.data!.model!;
            UserInfos.shared.saveToken(tokenModel.accessToken);
            widget.onThridLoginSuccess?.call();
          } else if (model.data?.boolValue != null) {
            // 处理bool情况
            final boolValue = model.data!.boolValue!;
            if(boolValue){
              loadingClickWord(context,0);
            }
          }
        } else {
          ToastUtils.showCenterToast(context, model.msg ?? '登录失败,请联系客服');
        }
      }
    } catch (e) {
      // 错误处理
      print('绑定登录失败: $e');
    }
  }
}
